package com.example.rlw.mvpplugintest.downfile;

import com.example.rlw.mvpplugintest.mvp.BasePresenterImpl;
import com.example.rlw.mvpplugintest.mvp.MyObservableTransformer;
import com.example.rlw.mvpplugintest.net.NetWorks;

import java.io.File;
import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 描述：下载文件的Presenter
 * Created by rlw on 2019/3/4.
 */
public class DownLoadPresenter extends BasePresenterImpl<DownLoadContract.IDownloadView> implements DownLoadContract.IDownloadPresenter {
    @Override
    public void downloadFile(String url) {

        DownloadService downloadService = NetWorks.configRetrofit(DownloadService.class, new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                return response.newBuilder().body(new ProgressResponseBody(response.body(),
                        new ProgressResponseBody.ProgressListener() {
                            @Override
                            public void onProgress(long totalSize, long downSize) {
                                getView().onProgress(totalSize, downSize);
                            }
                        })).build();
            }
        });

        downloadService.downloadFile(url)
                .compose(new MyObservableTransformer<ResponseBody>())
                .subscribe(new DownloadFileObsever(getView(), url) {
                    @Override
                    public void onSuccess(File file) {
                        getView().showSuccess(file);
                    }
                });
    }
}
